//
//  IdCardFaceViewController.m
//  DanaKreditLoan
//
//  Created by ZhengChengFeng on 2024/10/21.
//

#import "IdCardFaceViewController.h"
#import "IdCardSuccessViewController.h"

#import "OrderDetailModel.h"

#import "PersonInfoViewController.h"
#import "ContactInfoViewController.h"
#import "BankCardInfoViewController.h"

#import "CustomCameraController.h"

#define kFootViewHeight  (15 + 48 + (IS_IPhoneX_All ? kHeight_BottomSafe : 15))

@interface IdCardFaceViewController ()<CLLocationManagerDelegate>

@property (nonatomic) OrderDetailModel *orderDetModel;

@property (nonatomic) CLLocationManager *locationManager;
@property (nonatomic) NSTimer *timer;
@property (nonatomic) NSInteger timeInt;
@property (nonatomic) BOOL isLocationSuccess;
@property (nonatomic) NSString *startTimeStr1,*endTimeStr1;

@property (nonatomic) NSInteger type;

@property (nonatomic) CLLocationManager *locationManager2;
@property (nonatomic) NSTimer *timer2;
@property (nonatomic) NSInteger timeInt2;
@property (nonatomic) BOOL isLocationSuccess2;
@property (nonatomic) NSString *startTimeStr2,*endTimeStr2;

@end

@implementation IdCardFaceViewController

- (void)back{
    [[DKCore sharedDKCore] jumpWLAlertView:^{
        [[self getCurrentVC] jumpToPopControlClass:@"OrderDetailViewController"];
    }];
}

- (void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    [self.navigationController setNavigationBarHidden:NO animated:animated];
}

- (void)initFootView{

    UIView *bottomV = [[UIView alloc] initWithFrame:CGRectMake(0, kScreenHeight - kFootViewHeight - kNavigationBarHeight, kScreenWidth, kFootViewHeight)];
    bottomV.backgroundColor = kTableViewBackColor;
    [self.view addSubview:bottomV];
    
    
    UIButton *nextBtn = [[UIButton alloc] initWithFrame:CGRectMake(15, 15, kScreenWidth - 30, 48)];
    nextBtn.titleLabel.font = [UIFont fontWithName:kFuturaMedium size:16];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateNormal];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateSelected];
    [nextBtn setTitleColor:kWhiteColor forState:UIControlStateHighlighted];
    [nextBtn setTitle:ASLocalizedString(@"Next Step") forState:UIControlStateNormal];
    [nextBtn setTitle:ASLocalizedString(@"Next Step") forState:UIControlStateSelected];
    [nextBtn setTitle:ASLocalizedString(@"Next Step") forState:UIControlStateHighlighted];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateNormal];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateSelected];
    [nextBtn setImage:[UIImage imageNamed:@"icon_login2"] forState:UIControlStateHighlighted];
    [nextBtn addTarget:self action:@selector(clickAlbum) forControlEvents:UIControlEventTouchUpInside];
    nextBtn.backgroundColor = kButtonDefaultColor;
    nextBtn.layer.cornerRadius = 24;
    nextBtn.layer.masksToBounds = YES;
    [bottomV addSubview:nextBtn];
    [nextBtn setImgRightTitltLeft:10];

}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.tableView.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight - kFootViewHeight );
    
    [self initFootView];
    
    UIView *headView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, DimensionBaseIphone6(53 + 118 + 53 + 268))];
    self.tableView.tableHeaderView = headView;
    
    UIImageView *imgV1 = [[UIImageView alloc] initWithFrame:CGRectMake(20, DimensionBaseIphone6(53), kScreenWidth - 40, DimensionBaseIphone6(118))];
    imgV1.image = [UIImage imageNamed:@"icon_idcard1"];
    [headView addSubview:imgV1];
    
    UIImageView *imgV2 = [[UIImageView alloc] initWithFrame:CGRectMake((kScreenWidth - DimensionBaseIphone6(174))/2, DimensionBaseIphone6(20), DimensionBaseIphone6(174), DimensionBaseIphone6(176))];
    imgV2.image = [UIImage imageNamed:@"icon_idcard2"];
    [headView addSubview:imgV2];
    
    
    UIView *backV1 = [[UIView alloc] initWithFrame:CGRectMake(15, imgV1.bottom + DimensionBaseIphone6(53), kScreenWidth - 30, DimensionBaseIphone6(268))];
    backV1.backgroundColor = [UIColor whiteColor];
    [headView addSubview:backV1];
    backV1.layer.cornerRadius = 14;
    backV1.layer.masksToBounds = YES;
    
    
    
    UIView *line2 = [[UIView alloc] initWithFrame:CGRectMake((backV1.width - 48)/2+24, DimensionBaseIphone6(25), (backV1.width - 48)/2, DimensionBaseIphone6(8))];
    line2.backgroundColor = [UIColor colorWithHexString:@"#75FA8D"];
    [backV1 addSubview:line2];
    line2.layer.cornerRadius = DimensionBaseIphone6(4);
    line2.layer.masksToBounds = YES;
    
    UIView *line1 = [[UIView alloc] initWithFrame:CGRectMake(24, DimensionBaseIphone6(25), (backV1.width - 48)/2 + 2, DimensionBaseIphone6(8))];
    line1.backgroundColor = [UIColor colorWithHexString:@"#75FA8D"];
    [backV1 addSubview:line1];
    line1.layer.cornerRadius = DimensionBaseIphone6(4);
    line1.layer.masksToBounds = YES;
    
    UIImageView *lineV1 = [[UIImageView alloc] initWithFrame:CGRectMake(24 + (line1.width -11)/2 , line1.top - 1.5, 11, 11)];
    [backV1 addSubview:lineV1];
    lineV1.image = [UIImage imageNamed:@"icon_idcard3"];
    
    UIImageView *lineV2 = [[UIImageView alloc] initWithFrame:CGRectMake(line1.right + (line2.width-11)/2 , lineV1.top, 11, 11)];
    [backV1 addSubview:lineV2];
    lineV2.image = [UIImage imageNamed:@"icon_idcard3"];
    
    UILabel *lab1 = [UILabel createLabel:[UIFont fontWithName:kFutura size:13] color:[UIColor colorWithHexString:@"#03241B"]];
    lab1.text = ASLocalizedString(@"Aadhaar Front");
    [backV1 addSubview:lab1];
    lab1.textAlignment = 1;
    lab1.frame = CGRectMake(line1.left, lineV1.bottom, line1.width, DimensionBaseIphone6(20));
    
    UILabel *lab2 = [UILabel createLabel:[UIFont fontWithName:kFutura size:13] color:[UIColor colorWithHexString:@"#03241B"]];
    lab2.text = ASLocalizedString(@"Face");
    [backV1 addSubview:lab2];
    lab2.textAlignment = 1;
    lab2.frame = CGRectMake(line2.left, lineV2.bottom, line2.width, DimensionBaseIphone6(20));
    

    UIImageView *imgV3 = [[UIImageView alloc] initWithFrame:CGRectMake(backV1.width - 4 - 97, backV1.height - DimensionBaseIphone6(62) - 2, 97, DimensionBaseIphone6(62))];
    imgV3.image = [UIImage imageNamed:@"icon_idcard5"];
    [backV1 addSubview:imgV3];
    
    
    UIImageView *imgV4 = [[UIImageView alloc] initWithFrame:CGRectMake((backV1.width - DimensionBaseIphone6(155))/2, DimensionBaseIphone6(89), DimensionBaseIphone6(155), DimensionBaseIphone6(155))];
    imgV4.image = [UIImage imageNamed:@"icon_idcard13"];
    [backV1 addSubview:imgV4];
    

    UIImageView *imgV5 = [[UIImageView alloc] initWithFrame:CGRectMake((imgV4.width - DimensionBaseIphone6(45))/2, (imgV4.height - DimensionBaseIphone6(45))/2, DimensionBaseIphone6(45), DimensionBaseIphone6(45))];
    imgV5.image = [UIImage imageNamed:@"icon_idcard7"];
    [imgV4 addSubview:imgV5];
    
    
    backV1.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickAlbum)];
    [backV1 addGestureRecognizer:tap];
    
}

- (void)clickAlbum{
    [self.view endEditing:YES];
    AlertPhotoGuideView *alertV = [[AlertPhotoGuideView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight) withFace:YES];
    [[UIApplication sharedApplication].keyWindow addSubview:alertV];
    alertV.clickSureBlock = ^{
        [self goPhoto];
    };
    
}

- (void)goPhoto{
   
    
    [AuthorHelper isCanUseCamera:^{
        
        
        dispatch_async(dispatch_get_main_queue(), ^{
           
            [self go];
            
        });
        
    }];
    
}

- (void)go{
    
    self.startTimeStr1 = esString([NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"]);
    
    CustomCameraController *vc = [[CustomCameraController alloc] init];
    vc.isFront = YES;
    UINavigationController *naV = [[UINavigationController alloc]initWithRootViewController:vc];
    naV.modalPresentationStyle = UIModalPresentationOverFullScreen;
    [self presentViewController:naV animated:YES completion:nil];
    
    vc.callBackPhotoData = ^(NSData * _Nonnull imgData) {
        
        NSMutableDictionary *muDic = @{
            @"cultivate":@"2",
            @"lord":@"10",
            @"blankets":@"",
            @"colony":@"",
        }.mutableCopy;
        
        if ([CurrentUser mine].isYNLanguage) {
            muDic = @{
                @"lord":@"10",
                @"cultivate":@"2",
                @"colony":@"",
                @"amazing":@"1",
                @"set":@"setPic",
            }.mutableCopy;
        }
        [BoxLoadingHelper showBoxLoadingWithMessage:@""];
        [HttpNetHelper postUploadPhotoUrl:kUploadPicUrl params:muDic imageData:imgData name:@"boring" fileName:@"fileName.jpg" mimeType:@"image/jpeg" withProgress:^(double pro) {
            
        } success:^(NSDictionary * _Nonnull responseDic) {
            [BoxLoadingHelper hideBoxLoading];
            if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
                [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                return;
            }
            
            self.endTimeStr1 = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
            [self uploadMaiDianFaceData];
            
            [self enterNextPage];
            
        } failure:^(NSError * _Nonnull error) {
            [BoxLoadingHelper hideBoxLoading];
        }];
        
        
        
    };
    
    
}


/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

- (void)enterNextPage{
    
    [BoxLoadingHelper showBoxLoadingWithMessage:@""];
    NSMutableDictionary *muDic = @{
        @"largely":esString(self.idStr),
        @"mainland":@"mainlandOrderDet",
    }.mutableCopy;
    [HttpNetHelper postNetworkHelperForPath:kOrderDetailUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
        [BoxLoadingHelper hideBoxLoading];
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
        if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
            [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
            return;
        }
    
      
        NSDictionary *dic = responseDic[@"clip"];
       
        OrderDetailModel *model = [OrderDetailModel mj_objectWithKeyValues:dic];
        self.orderDetModel = model;
        
        if (PMObjectIsEmpty(model.swears)) {
            [self enterOrderH5Page];
            return;
        }
        if ([esString(model.swears.undiluted) isEqualToString:kPersonInfoVertify]) {
            [self goPersonalVertify];
        }
        else if ([esString(model.swears.undiluted) isEqualToString:kContactInfoVertify]) {
            [self goContactVertify];
        }
        else if ([esString(model.swears.undiluted) isEqualToString:kBankInfoVertify]) {
            [self goBankVertify];
        }

        
    } onCompleteFailur:^(NSError * _Nonnull error) {
        [BoxLoadingHelper hideBoxLoading];
        [BoxLoadingHelper hideBoxLoadingFromView:self.view];
    } withIsForm:YES];
    

}
    

- (void)enterOrderH5Page{
        NSMutableDictionary *muDic = @{
            @"dosed":esString(self.orderDetModel.refugees.passages),
            @"founders":esString(self.orderDetModel.refugees.founders),
            @"weakness":esString(self.orderDetModel.refugees.weakness),
            @"shouldered":esString(self.orderDetModel.refugees.shouldered),
            @"guiding":@"guidingIdStr",
            @"excuse":@"excuseIdStr",
        }.mutableCopy;

    self.startTimeStr2 = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];

        [BoxLoadingHelper showBoxLoadingWithMessage:@""];
        [HttpNetHelper postNetworkHelperForPath:kOrderNoUrl parameter:muDic onCompleteSuccess:^(NSDictionary * _Nonnull responseDic) {
            [BoxLoadingHelper hideBoxLoading];
            if ([responseDic[@"pineapples"] integerValue] != kSuccessCode) {
                [BoxLoadingHelper showBoxWithMessage:esString(responseDic[@"shin"])];
                return;
            }
            
            self.endTimeStr2 = [NSString getNowTimeTimestamp:@"yyyyMMdd HH:mm:ss"];
            [self uploadMaiDianSDStartData];
        
            NSDictionary *dic = responseDic[@"clip"];
            
            [[DKCore sharedDKCore] jumpToControllerWithUrlString:esString(dic[@"twentieth"])];
          
        } onCompleteFailur:^(NSError * _Nonnull error) {
            [BoxLoadingHelper hideBoxLoading];
        } withIsForm:YES];
        
}


- (void)goPersonalVertify{
    PersonInfoViewController *vc = [[PersonInfoViewController alloc] init];
    vc.idStr = esString(self.idStr);
    vc.orderNoStr = esString(self.orderNoStr);
    vc.title = esString(self.orderDetModel.swears.arrow);
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)goContactVertify{
    ContactInfoViewController *vc = [[ContactInfoViewController alloc] init];
    vc.idStr = esString(self.idStr);
    vc.orderNoStr = esString(self.orderNoStr);
    vc.title = esString(self.orderDetModel.swears.arrow);
    [self.navigationController pushViewController:vc animated:YES];
}


- (void)goBankVertify{
    BankCardInfoViewController *vc = [[BankCardInfoViewController alloc] init];
    vc.idStr = esString(self.idStr);
    vc.orderNoStr = esString(self.orderNoStr);
    vc.title = esString(self.orderDetModel.swears.arrow);
    [self.navigationController pushViewController:vc animated:YES];
}

#pragma mark ------- uploadMaiDianFaceData --------
- (void)uploadMaiDianFaceData{
    self.timeInt = 0;
    self.isLocationSuccess = NO;
    [self initLocation];
}

- (void)initLocation{
    self.timer = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(addTimer) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer forMode:NSRunLoopCommonModes];
    
    self.locationManager = [[CLLocationManager alloc]init];
    self.locationManager.delegate = self;
    self.locationManager.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager.distanceFilter = 100;
    [self.locationManager requestWhenInUseAuthorization];
    [self.locationManager requestLocation];
}

- (void)addTimer{
    self.timeInt ++;
    if (self.isLocationSuccess) {
        [self.timer invalidate];
        self.timer = nil;
        self.timeInt = 0;
    }
    else{
        if (self.timeInt > 8) {
            [self.timer invalidate];
            self.timer = nil;
            self.timeInt = 0;
            NSString *longitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLongitude];
            NSString *latitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLatitude];
            
            [self goServer1WithLongitudeStr:PMStringIsEmpty(longitudeStr) ? @"" : longitudeStr withLatitudeStr:PMStringIsEmpty(latitudeStr) ? @"" : latitudeStr];
            
        }
    }
}

- (void)locationManager:(CLLocationManager *)manager didUpdateLocations:(NSArray *)locations{
    
    CLLocation *newlocation = locations[0];
    NSString *longitudeStr = [NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude];
    NSString *latitudeStr =  [NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude];
    if (manager == self.locationManager) {
        [self.locationManager stopUpdatingLocation];
    } else {
        [self.locationManager2 stopUpdatingLocation];
    }
    
    
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] removeObjectForKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.longitude] forKey:kStoreLongitude];
    [[NSUserDefaults standardUserDefaults] setObject:[NSString stringWithFormat:@"%lf",newlocation.coordinate.latitude] forKey:kStoreLatitude];
    [[NSUserDefaults standardUserDefaults] synchronize];
    
    if (self.type == 2) {
        self.isLocationSuccess2 = YES;
        
        if (self.timeInt2 <= 8) {
            [self goServer2WithLongitudeStr:esString(longitudeStr) withLatitudeStr:esString(latitudeStr)];
        }
        
    } else {
        self.isLocationSuccess = YES;
        
        if (self.timeInt <= 8) {
            [self goServer1WithLongitudeStr:esString(longitudeStr) withLatitudeStr:esString(latitudeStr)];
        }
    }

}

- (void)goServer1WithLongitudeStr:(NSString *)longitudeStr withLatitudeStr:(NSString *)latitudeStr{
    [DataCategoryUpload uploadMaiDianData:@"3" withOrderIdStr:self.idStr withOrderNoStr:esString(self.orderNoStr) withLongitude:esString(longitudeStr) withLatitude:esString(latitudeStr) withStartTime:self.startTimeStr1 withEndTime:self.endTimeStr1];
}

- (void)goServer2WithLongitudeStr:(NSString *)longitudeStr withLatitudeStr:(NSString *)latitudeStr{
    [DataCategoryUpload uploadMaiDianData:@"8" withOrderIdStr:self.idStr withOrderNoStr:esString(self.orderNoStr) withLongitude:esString(longitudeStr) withLatitude:esString(latitudeStr) withStartTime:self.startTimeStr2 withEndTime:  self.endTimeStr2];
}

- (void)locationManager:(CLLocationManager *)manager didFailWithError:(NSError *)error{
    
}


#pragma mark ----- uploadMaiDianSDStartData ------
- (void)uploadMaiDianSDStartData{
    self.type = 2;
    self.timeInt2 = 0;
    self.isLocationSuccess2 = NO;
    [self initLocation2];
}

- (void)initLocation2{
    
    self.timer2 = [NSTimer timerWithTimeInterval:1.f target:self selector:@selector(addTimer2) userInfo:nil repeats:YES];
    [[NSRunLoop currentRunLoop] addTimer:self.timer2 forMode:NSRunLoopCommonModes];
    
    self.locationManager2 = [[CLLocationManager alloc]init];
    self.locationManager2.delegate = self;
    self.locationManager2.desiredAccuracy = kCLLocationAccuracyBest;
    self.locationManager2.distanceFilter = 100;
    [self.locationManager2 requestWhenInUseAuthorization];
    [self.locationManager2 requestLocation];
}

- (void)addTimer2{
    self.timeInt2 ++;
    if (self.isLocationSuccess2) {
        [self.timer2 invalidate];
        self.timer2 = nil;
        self.timeInt2 = 0;
    }
    else{
        if (self.timeInt2 > 8) {
            [self.timer2 invalidate];
            self.timer2 = nil;
            self.timeInt2 = 0;
            NSString *longitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLongitude];
            NSString *latitudeStr = [[NSUserDefaults standardUserDefaults] objectForKey:kStoreLatitude];
            
            [self goServer2WithLongitudeStr:PMStringIsEmpty(longitudeStr) ? @"" : longitudeStr withLatitudeStr:PMStringIsEmpty(latitudeStr) ? @"" : latitudeStr];
            
        }
    }
}


@end

